package de.slothsoft.wasbinich.core.util;

import java.lang.reflect.Field;

import de.slothsoft.wasbinich.core.FullPicture;
import de.slothsoft.wasbinich.core.Picture;

public final class PictureUtil {

    public static FullPicture getDifferences(FullPicture original, FullPicture newPicture) {
	FullPicture difference = new FullPicture();
	difference.id = original.id;
	int setFields = 0;
	try {
	    for (Field field : FullPicture.class.getDeclaredFields()) {
		Object originalValue = field.get(original);
		Object newValue = field.get(newPicture);
		if (!equals(originalValue, newValue)) {
		    field.set(difference, newValue);
		    setFields++;
		}
	    }
	} catch (Exception e) {
	    throw new RuntimeException(e); // should not happen
	}
	return setFields == 0 ? null : difference;
    }

    public static boolean equals(Object a, Object b) {
	return a == b || a != null && a.equals(b);

    }

    public static String createAlternativeAnswersString(String[] correctAnswers) {
	StringBuilder sb = new StringBuilder();
	for (int i = 1; i < correctAnswers.length; i++) {
	    if (i > 1) {
		sb.append(", "); //$NON-NLS-1$
	    }
	    sb.append(correctAnswers[i]);
	}
	return sb.toString();
    }

    public static boolean isCorrectAnswer(Picture picture, String answer) {
	for (String correctAnswer : picture.correctAnswers) {
	    if (correctAnswer.equalsIgnoreCase(answer))
		return true;
	}
	return false;
    }

    private PictureUtil() {
	// hit me baby one more time
    }
}
